<!DOCTYPE html>


<html lang="zh-CN">
  

    <head>
      <meta charset="utf-8" />
        
      <meta name="description" content="这个人很懒，什么都没留下" />
      
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>简单瀑布流布局实现（Swift） |  DJ Hong&#39;s BLOG</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.jpg" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="DJ Hong's BLOG" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-简单瀑布流布局实现（Swift）"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  简单瀑布流布局实现（Swift）
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2020/08/27/%E7%AE%80%E5%8D%95%E7%80%91%E5%B8%83%E6%B5%81%E5%B8%83%E5%B1%80%E5%AE%9E%E7%8E%B0%EF%BC%88Swift%EF%BC%89/" class="article-date">
  <time datetime="2020-08-27T13:21:38.000Z" itemprop="datePublished">2020-08-27</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/iOS/">iOS</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">1.2k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">5 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h3 id="写作目的"><a href="#写作目的" class="headerlink" title="写作目的"></a>写作目的</h3><p>前段时间面试，问了瀑布流布局，所以就想到写这篇文章分享一下相关的知识点。<br>瀑布流布局是一种常见的布局方式，它能够美观、灵活地展示不同高度的素材组合的视图控件。<br>瀑布流布局的特点就在于，item从上往下排列，每次item的放置位置，都是当前的最短列下方。</p>
<h3 id="主要的类"><a href="#主要的类" class="headerlink" title="主要的类"></a>主要的类</h3><ul>
<li>UICollectionView：视图</li>
<li>UICollectionViewFlowLayout：布局</li>
<li>UICollectionViewLayoutAttributes：item配置</li>
</ul>
<h3 id="需要重写的系统方法"><a href="#需要重写的系统方法" class="headerlink" title="需要重写的系统方法"></a>需要重写的系统方法</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">1) 准备布局（第一次布局和刷新时调用）</span><br><span class="line">override func prepare</span><br><span class="line">2) 设置视图内容的尺寸</span><br><span class="line">override var collectionViewContentSize: CGSize</span><br><span class="line">3) 返回计算好的属性数组</span><br><span class="line">override func layoutAttributesForElements(in rect: CGRect) -&gt; [UICollectionViewLayoutAttributes]?</span><br></pre></td></tr></table></figure>


<h3 id="准备工作"><a href="#准备工作" class="headerlink" title="准备工作"></a>准备工作</h3><h4 id="视图-amp-数据源"><a href="#视图-amp-数据源" class="headerlink" title="视图&amp;数据源"></a>视图&amp;数据源</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br></pre></td><td class="code"><pre><span class="line">import UIKit</span><br><span class="line"></span><br><span class="line">class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource &#123;</span><br><span class="line"></span><br><span class="line">    // 数据源</span><br><span class="line">    var dataArr = [Int]()</span><br><span class="line">    // 列数</span><br><span class="line">    let columnCount:Int = 3;</span><br><span class="line">    // 瀑布流布局</span><br><span class="line">    var flowLayout: WaterfallFlowLayout!</span><br><span class="line"></span><br><span class="line">    var collectionView: UICollectionView!</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    //MARK: - --- 视图已经加载</span><br><span class="line">    override func viewDidLoad() &#123;</span><br><span class="line">        super.viewDidLoad()</span><br><span class="line">        // 数据源，同时也是高度值（实际项目中应根据内容计算高度）</span><br><span class="line">        self.dataArr = [300,200,300,400,100,200,300,400,100,200,300,400,100,200,300,400]</span><br><span class="line">        self.createUI()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    //MARK: - --- 创建UI</span><br><span class="line">    func createUI()&#123;</span><br><span class="line">        // 创建collectionView视图 和 flowLayout布局</span><br><span class="line">        self.flowLayout = WaterfallFlowLayout()</span><br><span class="line">        self.flowLayout.dataArr = self.dataArr</span><br><span class="line">        let rect: CGRect = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: SCREEN_WIDTH, height: SCREEN_HEIGHT))</span><br><span class="line">        let collectionView = UICollectionView.init(frame: rect, collectionViewLayout:self.flowLayout)</span><br><span class="line">        collectionView.delegate = self</span><br><span class="line">        collectionView.dataSource = self</span><br><span class="line">        collectionView.backgroundColor = UIColor.white</span><br><span class="line">        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: &quot;HomeCell&quot;)</span><br><span class="line">        self.view.addSubview(collectionView)</span><br><span class="line">        self.collectionView = collectionView</span><br><span class="line"></span><br><span class="line">        // 设置布局属性</span><br><span class="line">        self.setWaterfallFlowLayouts()</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    //MARK: - --- 设置item的布局</span><br><span class="line">    func setWaterfallFlowLayouts()&#123;</span><br><span class="line">        // 设置布局属性</span><br><span class="line">        self.flowLayout.columnCount = self.columnCount</span><br><span class="line">        // 边界</span><br><span class="line">        self.flowLayout.sectionInset = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)</span><br><span class="line">        // 设置间距</span><br><span class="line">        self.flowLayout.minimumLineSpacing = 10.0</span><br><span class="line">        self.flowLayout.minimumInteritemSpacing = 10.0</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    //MARK: - --- delegate，dataSource</span><br><span class="line">    func numberOfSections(in collectionView: UICollectionView) -&gt; Int &#123;</span><br><span class="line">        return 1</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int &#123;</span><br><span class="line">        return self.dataArr.count</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell &#123;</span><br><span class="line">        let cell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;HomeCell&quot;, for: indexPath)</span><br><span class="line">        cell.backgroundColor = .red</span><br><span class="line">        cell.layer.cornerRadius = 8</span><br><span class="line">        cell.layer.masksToBounds = true</span><br><span class="line"></span><br><span class="line">        var label: UILabel!</span><br><span class="line"></span><br><span class="line">        if let lab: UILabel = cell.contentView.subviews.last as? UILabel&#123;</span><br><span class="line">            label = lab</span><br><span class="line">        &#125;else&#123;</span><br><span class="line">            label = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30))</span><br><span class="line">            label.textAlignment = .center</span><br><span class="line">            cell.contentView.addSubview(label)</span><br><span class="line">            label.textColor = .white</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        label.text = &quot;\(indexPath.row)&quot;</span><br><span class="line">        return cell</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) &#123;</span><br><span class="line">        // 点击添加数据</span><br><span class="line">        self.dataArr += [300,200,300,400,100,200,300,400,100,200,300,400,100,200,300,400]</span><br><span class="line">        self.flowLayout.dataArr = self.dataArr</span><br><span class="line">        self.collectionView.reloadData()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>


<h3 id="核心代码"><a href="#核心代码" class="headerlink" title="核心代码"></a>核心代码</h3><h4 id="计算布局"><a href="#计算布局" class="headerlink" title="计算布局"></a>计算布局</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br></pre></td><td class="code"><pre><span class="line">let SCREEN_WIDTH = UIScreen.main.bounds.size.width</span><br><span class="line">let SCREEN_HEIGHT = UIScreen.main.bounds.size.height</span><br><span class="line"></span><br><span class="line">class WaterfallFlowLayout: UICollectionViewFlowLayout &#123;</span><br><span class="line">    // 总列数</span><br><span class="line">    var columnCount:Int = 0</span><br><span class="line">    // 数据数组</span><br><span class="line">    var dataArr = [Int]()</span><br><span class="line">    // 整个collectionView的高度</span><br><span class="line">    private var maxH:Int?</span><br><span class="line">    //所有item的属性</span><br><span class="line">    fileprivate var layoutAttributesArray = [UICollectionViewLayoutAttributes]()</span><br><span class="line"></span><br><span class="line">    // 准备布局时调用</span><br><span class="line">    override func prepare() &#123;</span><br><span class="line">        /**</span><br><span class="line">         *  计算每个item的宽度</span><br><span class="line">         *  即：(collectionView的宽度 - 左右边距和 - item的水平间距之和) / 每行的item数量</span><br><span class="line">         */</span><br><span class="line">        let itemWidth = ((self.collectionView?.bounds.size.width)! - self.sectionInset.left - self.sectionInset.right - self.minimumInteritemSpacing * CGFloat(self.columnCount - 1)) / CGFloat.init(self.columnCount)</span><br><span class="line"></span><br><span class="line">        // 通过item的宽度，计算并设置属性</span><br><span class="line">        self.computeAttributesWithItemWidth(CGFloat(itemWidth))</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ///根据itemWidth计算布局属性</span><br><span class="line">    func computeAttributesWithItemWidth(_ itemWidth:CGFloat)&#123;</span><br><span class="line"></span><br><span class="line">        // 定义一个列高数组 记录每一列的总高度（初始值都为上边距）</span><br><span class="line">        var columnHeightArr = [Int](repeating: Int(self.sectionInset.top), count: self.columnCount)</span><br><span class="line">        // 定义一个 记录每一列的item个数的数组</span><br><span class="line">        var columnItemCountArr = [Int](repeating: 0, count: self.columnCount)</span><br><span class="line"></span><br><span class="line">        // 定义一个 存储属性的临时数组</span><br><span class="line">        var attributesArray = [UICollectionViewLayoutAttributes]()</span><br><span class="line"></span><br><span class="line">        // 遍历数据计算每个item的属性并布局</span><br><span class="line">        for (index, dj_height) in self.dataArr.enumerated() &#123;</span><br><span class="line"></span><br><span class="line">            // 根据IndexPath获取Cell元素的属性</span><br><span class="line">            let attributes = UICollectionViewLayoutAttributes.init(forCellWith: IndexPath.init(item: index, section: 0))</span><br><span class="line">            // 找出最短列的下标</span><br><span class="line">            let minHeight:Int = columnHeightArr.sorted().first!</span><br><span class="line">            let column = columnHeightArr.firstIndex(of: minHeight)</span><br><span class="line"></span><br><span class="line">            // 将数据追加在最短列</span><br><span class="line">            columnItemCountArr[column!] += 1</span><br><span class="line">            // 计算该项的坐标</span><br><span class="line">            let itemX = (itemWidth + self.minimumInteritemSpacing) * CGFloat(column!) + self.sectionInset.left</span><br><span class="line">            let itemY = minHeight</span><br><span class="line">            // 计算item的高度（机型适配，注意比例缩放）</span><br><span class="line">            let itemH = dj_height</span><br><span class="line">            // 设置frame</span><br><span class="line">            attributes.frame = CGRect(x: itemX, y: CGFloat(itemY), width: itemWidth, height: CGFloat(itemH))</span><br><span class="line"></span><br><span class="line">            attributesArray.append(attributes)</span><br><span class="line">            // 累加列高</span><br><span class="line">            columnHeightArr[column!] += itemH + Int(self.minimumLineSpacing)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        // 找出最高列的下标</span><br><span class="line">        let maxHeight:Int = columnHeightArr.sorted().last!</span><br><span class="line">        let maxHeightColumnIndex = columnHeightArr.firstIndex(of: maxHeight)</span><br><span class="line">        // 根据最高列设置itemSize的默认值 使用总高度的平均值</span><br><span class="line">        let itemH = (maxHeight - Int(self.minimumLineSpacing) * (columnItemCountArr[maxHeightColumnIndex!] + 1)) / columnItemCountArr[maxHeightColumnIndex!]</span><br><span class="line">        self.itemSize = CGSize(width: itemWidth, height: CGFloat(itemH))</span><br><span class="line">        // 给属性数组设置数值</span><br><span class="line">        self.layoutAttributesArray = attributesArray</span><br><span class="line">        // 将最高列的行高赋值给属性，作为contentSize.Height的值</span><br><span class="line">        self.maxH = maxHeight</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    // 返回计算好的layoutAttributesArray数组</span><br><span class="line">    override func layoutAttributesForElements(in rect: CGRect) -&gt; [UICollectionViewLayoutAttributes]? &#123;</span><br><span class="line"></span><br><span class="line">        return self.layoutAttributesArray</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    // 重写设置contentSize</span><br><span class="line">    override var collectionViewContentSize: CGSize &#123;</span><br><span class="line">        get &#123;</span><br><span class="line">            return CGSize(width: (collectionView?.bounds.width)!, height: CGFloat(self.maxH!))</span><br><span class="line">        &#125;</span><br><span class="line">        set &#123;</span><br><span class="line">            self.collectionViewContentSize = newValue</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>本篇文章主要是对瀑布流的原理进行概述和提供思路，不涉及网络请求，动态内容计算等方面，应该还算是简单易懂的。感兴趣童鞋的可以<a target="_blank" rel="noopener" href="https://github.com/a334713698/WaterfallFlow">Github</a>上下载，欢迎交流学习。</p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://hongdongjie.gitee.io/2020/08/27/%E7%AE%80%E5%8D%95%E7%80%91%E5%B8%83%E6%B5%81%E5%B8%83%E5%B1%80%E5%AE%9E%E7%8E%B0%EF%BC%88Swift%EF%BC%89/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Swift/" rel="tag">Swift</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/08/28/LeetCode%E7%AE%97%E6%B3%95%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B0%EF%BC%882020%E5%B9%B48%E6%9C%88%EF%BC%89/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            LeetCode算法学习日记（2020年8月）
          
        </div>
      </a>
    
    
      <a href="/2020/05/08/2020%E5%B9%B45%E6%9C%88%E8%AF%BB%E4%B9%A6%E5%BF%83%E5%BE%97/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">2020年5月读书心得</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "evJAWdDwf7wWhHoUPfm3Njb6-gzGzoHsz",
    app_key: "z76x0RgTfVfauSSB6kV2xGUl",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2018-2022
        <i class="ri-heart-fill heart_icon"></i> GG266
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
      <li>
          <img src="/images/beian.png"></img>
          <a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=33010902002204" target="_black" rel="nofollow">浙公网安备 33010902002204号</a>
      </li>
        
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s4.cnzz.com/z_stat.php?id=1280804963&amp;web_id=1280804963'></script>
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="DJ Hong&#39;s BLOG"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/alipay.JPG">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://gitee.com/hongdongjie/gg266picgo/raw/master/pic4blog/wechat.JPG">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    <div id="music">
    
    
    
    <iframe frameborder="no" border="1" marginwidth="0" marginheight="0" width="200" height="52"
        src="//music.163.com/outchain/player?type=2&id=1908797593&auto=1&height=32"></iframe>
</div>

<style>
    #music {
        position: fixed;
        right: 15px;
        bottom: 0;
        z-index: 998;
    }
</style>
    
    

  </div>
</body>

</html>